package book.service.impl;

import book.dao.book.BookDao;
import book.dao.book.impl.BookDaoImpl;
import book.util.DbHelper;
import book.pojo.Book;
import book.pojo.DynamicParameter;
import book.pojo.PageBean;
import book.service.IBookService;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class IBookServiceImpl implements IBookService {
    BookDao bookDao = new BookDaoImpl();

    @Override
    public int addBook(Book book) {
        return bookDao.addBook(book);
    }

    @Override
    public List<Book> findAllBooks() {
        return bookDao.findAllBooks();
    }

    @Override
    public PageBean<Book> findAllBooks(PageBean<Book> pageBean) {
        return bookDao.findAllBooks(pageBean);
    }

    @Override
    public int getBookCount(PageBean<Book> pageBean) {
        try {
            int count = 0;
            //1、创建Query对象，将数据源对象为参数，runner内部使用完连接会自动返回连接池
            QueryRunner runner = new QueryRunner(DbHelper.getDataSource());

            //*******修改的代码**********//
            //2、编写sql
            //String sql = "select count(*) from t_user ";
            DynamicParameter parameter = pageBean.getParameter();
            parameter.setBaseSql("select count(*) from books ");
            //添加两个分页查询参数
            String sql = parameter.generateSqlForTotalCount();

            //取得动态传参的参数值，转换为数组
            Object []args = parameter.getParamValueList().toArray();
            //*******修改的代码**********//

            //3、执行查询，返回结果
            count = ((Long)runner.query(sql,new ScalarHandler(),args)).intValue();
            return count;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Book findBookById(int id) {
        return bookDao.findBookById(id);
    }

    @Override
    public int updataBook(Book book) {
        return bookDao.updateBook(book);
    }

    @Override
    public int deleteBook(Book book) {
        return bookDao.deleteBook(book);
    }


}
